package com.zsc.wxapp.controller.common;

import com.zsc.wxapp.entity.User;
import com.zsc.wxapp.entity.dto.UserLoginDTO;
import com.zsc.wxapp.entity.vo.UserLoginVO;
import com.zsc.wxapp.properties.JwtProperties;
import com.zsc.wxapp.result.Result;
import com.zsc.wxapp.services.UserService;
import com.zsc.wxapp.utils.JwtUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

@RestController("loginController")
@RequestMapping("/api/wxapp/common")
//@Api(tags = "用户登录注册相关接口")
@Slf4j
public class LoginController {

    @Resource
    private JwtProperties jwtProperties;
    @Resource
    private UserService userService;

    @PostMapping("/login")
//    @ApiOperation("用户登录")
//    @ApiImplicitParam(name = "userLoginDTO", value = "用户登录信息", required = true, dataTypeClass = UserLoginDTO.class)
    public Result<UserLoginVO> login(@RequestBody UserLoginDTO userLoginDTO) {
        log.info("用户登录：{}", userLoginDTO);

        User user;
        try {
            user = userService.login(userLoginDTO);
        } catch (RuntimeException e) {
            String msg = e.getMessage();
            try {
                msg = URLEncoder.encode(msg, String.valueOf(StandardCharsets.UTF_8));
            } catch (UnsupportedEncodingException e1) {
                log.error("编码失败，本次要编码的内容是：{}", msg);
                return null;
            }
            return Result.error(e.getMessage());
        }

        Map<String, Object> claims = new HashMap<>();
        claims.put("userId", user.getUserId());
        String token = JwtUtils.createJWT(jwtProperties.getSecretKey(), jwtProperties.getTtl(), claims);

        UserLoginVO userLoginVO = UserLoginVO.builder()
                .userId(user.getUserId())
                .phone(user.getPhone())
                .token(token)
                .permission(user.getPermission())
                .build();

        return Result.success(userLoginVO);
    }
}
